package com.ruoyi.chat.http;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.chat.constant.RagFlowCode;
import com.ruoyi.chat.exception.ragFlowReqException;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

@Configuration
public class RagFlowUtils {

    private static final Logger log = LoggerFactory.getLogger(RagFlowUtils.class);

    private static String prefix;

    @Value("${rag_flow.url_prefix}")
    public void setPrefix(String prefix) {
        RagFlowUtils.prefix = prefix;
    }

    private static final String APIKEY = "Bearer ragflow-RjMGI5ZWZjMDQ4YjExZjA4ODQxMDI0Mm";

    /**
     * post请求regFlow普通http接口
     *
     * @param chatUrl 请求地址
     * @param param 请求参数
     * @return 返回信息
     */
    public static JSONObject sendPost(String chatUrl, JSONObject param) {
        String result = HttpUtils.sendPost(prefix + chatUrl, param.toJSONString(), MediaType.APPLICATION_JSON_VALUE, APIKEY);
        return handleResult(result);
    }

    public static JSONObject sendPut(String chatUrl, JSONObject param) {
        String result = HttpUtils.sendPut(prefix + chatUrl, param.toJSONString(), MediaType.APPLICATION_JSON_VALUE, APIKEY);
        return handleResult(result);
    }

    public static JSONObject sendDelete(String chatUrl, JSONObject param) {
        String result = HttpUtils.sendDelete(prefix + chatUrl, param.toJSONString(), MediaType.APPLICATION_JSON_VALUE, APIKEY);
        return handleResult(result);
    }

    public static JSONObject handleResult(String result) {
        String msg = StringUtils.EMPTY;
        String code;
        JSONObject json;
        try {
            json = JSONObject.parseObject(result);
            msg = String.valueOf(json.get(RagFlowCode.MESSAGE));
            code = String.valueOf(json.get(RagFlowCode.CODE));
            if (!RagFlowCode.CODE_SUCCESS.equals(code)) {
                throw new ragFlowReqException(msg);
            }
        } catch (Exception e) {
            throw new ragFlowReqException(msg);
        }
        return json;
    }
}
